package com.jxnd.sunflower.service.Impl;

import com.jxnd.sunflower.domain.RUser;
import com.jxnd.sunflower.domain.bo.LoginBO;
import com.jxnd.sunflower.domain.bo.RetrievePsswordBO;
import com.jxnd.sunflower.domain.bo.UserBO;
import com.jxnd.sunflower.domain.dto.UserDTO;
import com.jxnd.sunflower.exception.SunFlowerException;
import com.jxnd.sunflower.mapper.RUserMapper;
import com.jxnd.sunflower.service.UserService;
import com.jxnd.sunflower.task.EmailTask;
import com.jxnd.sunflower.utils.JwtToken;
import com.jxnd.sunflower.utils.LocalUser;
import com.jxnd.sunflower.utils.MD5Utils;
import com.jxnd.sunflower.utils.RedisOperator;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Locale;

/**
 * @author: 敷衍
 * @description:
 * @date: 2021/11/21 11:02
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {


    private  final  String STATE_STOP = "1";
    private  final  String STATE_START = "0";

    //默认头像
    private  final  String photo = "https://wx2.sinaimg.cn/bmiddle/006WjMqXgy1gvy5wn1gm1j30u00u078j.jpg";



    @Autowired
    private RUserMapper userMapper;

    @Autowired
    private EmailTask emailTask;

    @Autowired
    private RedisOperator redis;

    @Value("${rose.redis.time}")
    private Integer redisTime;


    @Override
    public boolean queryEmailExist(String email) {
        String result = userMapper.queryEmailExist(email);
        return result == null ? false : true;
    }


    @Override
    public String addUser(UserBO userBO) {

        RUser user = new RUser();
        user.setNickname(userBO.getNickname());
        String salt = ((int)((Math.random()*9+1)*100000)) + "";
        user.setSalt(salt);
        //密码加密 md5 加 随机盐值 混淆加密
        String newPassWord = MD5Utils.getMD5Str(userBO.getPassword() + salt);
        user.setPassword(newPassWord);
        user.setState(STATE_START);
        user.setEmail(userBO.getEmail());
        user.setCreateTime(new Date());
        user.setPhoto(photo);
        userMapper.insertUser(user);
        //获取注册者的唯一Id 通过jwt加密返回回去
        Integer id = user.getId();

        String token = JwtToken.createToken(id);

        return token;
    }

    @Override
    public int RetrievePassword(RetrievePsswordBO bo) {
        boolean value = queryEmailExist(bo.getEmail());
        if(!value){
            throw new SunFlowerException("该用户不存在");
        }
        //密码加密 md5 加 随机盐值 混淆加密
        bo.setPassword(MD5Utils.getMD5Str(bo.getPassword() + bo.getCode())) ;

        int result = userMapper.RetrievePassword(bo);

        if(result==0){
            throw new SunFlowerException("修改失败");
        }

        return result;
    }


    @Override
    public void emailCode(String email) {
        //查询数据库 数据库里有数据 则静止再发邮件
        String value = redis.get(email);

        if(value!=null){
            throw new SunFlowerException("请不要频繁注册",501);
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(email);
        String code = ((int)((Math.random()*9+1)*100000)) + ""; //6位验证码
        //放入redis
        redis.set(email,code,redisTime);
        //发送邮件
//        message.setSubject("欢迎注册");
//        message.setText("您的注册码  "+ code+   "请尽快注册5分钟内有效");
//        emailTask.sendAsync(message);
    }

    @Override
    public String login(LoginBO bo) {
        RUser user = userMapper.login(bo);
        //把用户信息放进 ThreadLocal

        if(user==null){
            throw new SunFlowerException("用户名错误");
        }

        //加密密码
        String password = MD5Utils.getMD5Str(bo.getPassword() + user.getSalt());
        //密码比对
        if(!password.equals(user.getPassword())){
            throw new SunFlowerException("密码错误 请重新输入密码");
        }


        String token = JwtToken.createToken(user.getId());



        return token;
    }

    @Override
    public UserDTO userInfo(Integer id) {
        UserDTO userDTO = userMapper.queryUserInfo(id);
        return userDTO;
    }
}
